import { _decorator, Color, Component, Node, resources, Sprite, SpriteFrame, tween, Vec3 } from 'cc';
import { CardData } from './CardData';
import { Card } from './Card';
const { ccclass, property } = _decorator;

@ccclass('PokerCard')
export class PokerCard extends Component {
    @property(Sprite)
    front: Sprite = null!;

    @property(Sprite)
    back: Sprite = null!;

    // 新增属性
    @property(Color)
    highlightColor: Color = new Color(255, 255, 0, 255); // 高亮颜色

    private _data: CardData;
    private _isFaceUp = false;
    private originalPos: Vec3 = new Vec3();
    private isSelected: boolean = false;

    onLoad() {
        // 保存初始位置
        this.originalPos = this.node.position.clone();
        
        // 添加触摸事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouch, this);
    }

    get data() { return this._data; }

    init(data: CardData, isFaceUp: boolean) {
        if (!this.node.isValid) return; // 增加有效性检查
        if (!data) {
            console.error("Invalid card data!", this.node.name);
            this.node.destroy();
            return;
        }

        this._data = data;
        this._isFaceUp = isFaceUp;
        this.back.node.active = !isFaceUp;
        this.loadSpriteFrame();
    }

    private onTouch() {
        this.toggleSelectState();
    }

    private toggleSelectState() {
        this.isSelected = !this.isSelected;
        
        const targetY = this.isSelected ? 
            this.originalPos.y + 30 : 
            this.originalPos.y;
        
        // 动画效果
        tween(this.node)
            .to(0.2, {
                position: new Vec3(this.node.position.x, targetY, 0),
                scale: this.isSelected ? new Vec3(1.1, 1.1, 1) : Vec3.ONE
            })
            .call(() => {
                this.updateHighlight();
            })
            .start();
    }

    private updateHighlight() {
        const sprite = this.front.getComponent(Sprite)!;
        sprite.color = this.isSelected ? 
            this.highlightColor : 
            Color.WHITE;
    }

    private async loadSpriteFrame() {
        try {
            const path = this.getResourcePath();
            const frame = await new Promise<SpriteFrame>((resolve, reject) => {
                resources.load(path, SpriteFrame, (err, asset) => {
                    err ? reject(err) : resolve(asset);
                });
            });
            this.front.spriteFrame = frame;
        } catch (err) {
            console.error("Load card failed:", err);
            this.node.destroy();
        }
    }

    private getResourcePath(): string {
        const card = new Card(
            this._data.suit - 1,
            this._data.value,
            `${this._data.suit}_${this._data.value}`
        );
        return `textures/${card.spriteFramePath}/spriteFrame`;
    }

    flipCard(duration: number = 0.3) {
        tween(this.back.node)
            .to(duration/2, { scale: new Vec3(0, 1, 1) })
            .call(() => {
                this._isFaceUp = !this._isFaceUp;
                this.back.node.active = !this._isFaceUp;
                this.front.node.active = this._isFaceUp;
            })
            .to(duration/2, { scale: Vec3.ONE })
            .start();
    }

    // 重置状态（在出牌后调用）
    public resetState() {
        this.isSelected = false;
        this.node.position = this.originalPos.clone();
        this.updateHighlight();
    }
}


